package com.yuzhyn.hiops.app.utils;

import com.jcraft.jsch.*;
import com.yuzhyn.azylee.core.datas.exceptions.ExceptionTool;
import com.yuzhyn.azylee.core.logs.Alog;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class SSHTool {


    public static List<String> executeCommand(Session session, String command) {
        List<String> result = null;
        try {
            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(command);         //添加传入进来的shell命令
            channelExec.setInputStream(null);
            channelExec.setErrStream(System.err);//通道连接错误信息提示
            channelExec.connect();
            Alog.i("start execute channel command!");
            BufferedReader in = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            String msg;
            Alog.i("start read!");
            result = new ArrayList<>();
            while ((msg = in.readLine()) != null) {
                result.add(msg);
                Alog.i("命令返回信息：" + msg);
            }
            in.close();
            channelExec.disconnect();
            Alog.i("end execute channel command!");
            return result;
        } catch (Exception ex) {
            return result;
        } finally {

        }
    }


    public static void closeShell(Channel channel) {
        try {
            if (channel != null) {
                channel.disconnect();
            }
        } catch (Exception ex) {
            Alog.e(ExceptionTool.getStackTrace(ex));
        }
    }

    public static void closeSession(Session session) {
        try {
            if (session != null) {
                session.disconnect();
            }
        } catch (Exception ex) {

        }
    }

//    public static String exeCommand(String host, int port, String user, String password, String command) throws JSchException, IOException {
//
//        JSch jsch = new JSch();
//        Session session = jsch.getSession(user, host, port);
//        session.setConfig("StrictHostKeyChecking", "no");
//        //    java.util.Properties config = new java.util.Properties();
//        //   config.put("StrictHostKeyChecking", "no");
//
//        session.setPassword(password);
//        session.connect();
//
//        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
//        InputStream in = channelExec.getInputStream();
//        channelExec.setCommand(command);
//        channelExec.setErrStream(System.err);
//        channelExec.connect();
//        String out = IOUtils.toString(in, "UTF-8");
//
//        channelExec.disconnect();
//        session.disconnect();
//
//        return out;
//    }

}
